package com.emm.yixun.mobile.ui.web

import android.Manifest.permission.*
import android.annotation.SuppressLint
import android.app.Activity
import android.app.PendingIntent.getActivity
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.*
import android.webkit.*
import android.widget.ImageView
import android.widget.PopupWindow
import android.widget.RelativeLayout
import android.widget.TextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.emm.yixun.mobile.R
import com.emm.yixun.mobile.application.EmmApplication
import com.emm.yixun.mobile.base.BaseActivity
import com.emm.yixun.mobile.model.GetConsultantList
import com.emm.yixun.mobile.ui.from.NewFromActivity
import com.emm.yixun.mobile.ui.web.helper.HttpHelper
import com.emm.yixun.mobile.ui.web.helper.HttpHelper.distributionConsultant
import com.emm.yixun.mobile.ui.web.helper.WebHelper
import com.emm.yixun.mobile.ui.web.helper.WebHelper.Companion.CUSTOMER_DETAIL
import com.eroad.product.tools.PickerView
import com.tbruyelle.rxpermissions2.RxPermissions
import kotlinx.android.synthetic.main.activity_web.*
import kotlinx.android.synthetic.main.main_head_title.*
import org.jetbrains.anko.startActivity
import org.json.JSONObject
import java.util.HashMap

class WebActivity : BaseActivity() {

    private val mActions = mutableListOf<Pair<String, Int>>()

    private val mAdapter: BaseQuickAdapter<Pair<String, Int>, BaseViewHolder> =
        object : BaseQuickAdapter<Pair<String, Int>, BaseViewHolder>(R.layout.item_pop_more, mActions) {
            override fun convert(helper: BaseViewHolder, item: Pair<String, Int>) {
                helper.run {
                    setText(R.id.tv_title, item.first)
                    setImageResource(R.id.iv_icon, item.second)
                }
            }
        }

    private lateinit var mMorePopup: PopupWindow
    private lateinit var mDistributionPopup: PopupWindow

    private lateinit var mUrl: String
    private lateinit var mTitle: String

    private lateinit var mWebHelper: WebHelper

    private lateinit var mConsultantPickerView: PickerView

    private val mConsultants = mutableListOf<GetConsultantList.ConsultantList>()
    private var mSelectedConsultantName: String? = null

    override fun onCreate(bundle: Bundle?) {
        super.onCreate(bundle)
        setContentView(R.layout.activity_web)
        SetRelativiLayoutPadding(R.id.main_head_top_rela)
        initData()
        initView()
        initWebView()
        initPopupWindow()

        webView.loadUrl(mUrl)
    }

    override fun onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack()
        } else {
            super.onBackPressed()
        }
    }

    private fun initData() {
        intent.run {
            mUrl = getStringExtra(KEY_URL)
            mTitle = getStringExtra(KEY_TITLE)
        }

        mWebHelper = WebHelper(this)
    }

    private fun initView() {
        title_main.text = mTitle
        back_btn.setOnClickListener { onBackPressed() }

        more_btn.setOnClickListener {
            showMoreView(webView.url, main_head_top_rela)
        }
    }

    private fun showMoreView(url: String, tagView: View) {
        if (url.contains(CUSTOMER_DETAIL)) {
            mAdapter.replaceData(getCustomerDetailMoreActions())

            if (!mMorePopup.isShowing) {
                mMorePopup.showAsDropDown(tagView)
            }
        }
    }

    @SuppressLint("AddJavascriptInterface", "SetJavaScriptEnabled")
    private fun initWebView() {
        webView.run {
            settings.setSupportZoom(false)
            settings.databaseEnabled = true
            settings.blockNetworkImage = false
            settings.userAgentString = UA
            settings.javaScriptEnabled = true
            settings.builtInZoomControls = true
            settings.displayZoomControls = false
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
            }
            settings.setAppCacheEnabled(true)
            //设置 缓存模式
            settings.cacheMode = WebSettings.LOAD_DEFAULT
            // 开启 DOM storage API 功能
            settings.domStorageEnabled = true

            webChromeClient = object : WebChromeClient() {
                override fun onProgressChanged(view: WebView, newProgress: Int) {
                    super.onProgressChanged(view, newProgress)
                    seekBar.progress = newProgress
                    if (newProgress >= 100) {
                        showMoreButton(view.url)
                        title_main.text = view.title
                        seekBar.visibility = View.GONE
                    } else {
                        seekBar.visibility = View.VISIBLE
                    }
                }
            }

            webViewClient = object : WebViewClient() {
                override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                    return mWebHelper.shouldOverrideUrlLoading(view, url)
                }
            }
        }
    }

    private fun initPopupWindow() {
        initMorePopupWindow()
        initDistributionPopupWindow()
    }

    private fun initMorePopupWindow() {
        mAdapter.setOnItemClickListener { _, _, position ->
            mMorePopup.dismiss()
            when (mActions[position].first) {
                "添加到通讯录" -> add2Contacts()
                "分配" -> distribution()
                "新增认筹" -> addRecruit()
            }
        }

        val view = LayoutInflater.from(this).inflate(R.layout.pop_more, null)
        mMorePopup = PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
        // 设置焦点
        mMorePopup.isFocusable = true
        mMorePopup.isOutsideTouchable = true
        // view的焦点
        view.isFocusable = true
        view.isFocusableInTouchMode = true
        // 监听back按钮
        view.setOnKeyListener { _, keyCode, _ ->
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                mMorePopup.dismiss()
            }
            false
        }

        view.setOnClickListener { mMorePopup.dismiss() }

        view.findViewById<RecyclerView>(R.id.recyclerView).run {
            layoutManager = LinearLayoutManager(context)
            adapter = mAdapter
        }
    }

    private fun initDistributionPopupWindow() {
        val view = LayoutInflater.from(this).inflate(R.layout.popu_zp, null)
        mDistributionPopup = PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
        mDistributionPopup.isFocusable = true
        mDistributionPopup.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
        mDistributionPopup.isOutsideTouchable = true
        view.isFocusable = true
        view.isFocusableInTouchMode = true
        view.setOnKeyListener { _, keyCode, _ ->
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                mDistributionPopup.dismiss()
            }
            false
        }

        mConsultantPickerView = view.findViewById(R.id.select_pick) as PickerView

        view.setOnClickListener {
            mDistributionPopup.dismiss()
        }

        view.findViewById<ImageView>(R.id.dis_btn).setOnClickListener {
            mDistributionPopup.dismiss()
        }

        view.findViewById<RelativeLayout>(R.id.relative_all).setOnClickListener {
            // 消耗点击事件
        }

        view.findViewById<TextView>(R.id.shuerbtn).setOnClickListener {
            mDistributionPopup.dismiss()
            mConsultants.firstOrNull {
                mSelectedConsultantName == it.consultantUserName
            }?.let {
                mWebHelper.doAfterGetCustomerDetail(webView) { detail ->
                    distributionConsultant(this, it.consultantUserId, detail.customerId)
                }
            }
        }

        mConsultantPickerView.setOnSelectListener { text, _ ->
            mSelectedConsultantName = text
        }

        mConsultantPickerView.setSelected(0)
    }

    private fun showMoreButton(url: String) {
        more_btn.visibility = if (url.contains(CUSTOMER_DETAIL)) {
            View.VISIBLE
        } else {
            View.GONE
        }
    }

    private fun add2Contacts() {
        mWebHelper.doAfterGetCustomerDetail(webView) {
            val name = it.customerName ?: ""
            val tel = it.customerPhone ?: ""
            add2Contacts(name, tel)
        }
    }

    @SuppressLint("CheckResult")
    private fun add2Contacts(name: String, tel: String) {
        RxPermissions(this).request(WRITE_CONTACTS)
            .subscribe {
                if (it) {
                    if (Util.insertUser2Contacts(this, name, tel)) {
                        EmmApplication.T("已成功添加到通讯录")
                    } else {
                        EmmApplication.T("添加到通讯录失败！请检查信息和权限是否正确")
                    }
                } else {
                    EmmApplication.T("获取权限失败")
                }
            }
    }

    private fun distribution() {
        HttpHelper.getConsultantList(this) {
            showDistributionPopupWindow(it)
        }
    }


    private fun showDistributionPopupWindow(consultants: List<GetConsultantList.ConsultantList>) {
        val list = ArrayList<String>()

        mConsultants.run {
            clear()
            addAll(consultants)
            forEach {
                list.add(it.consultantUserName)
            }
        }

        mConsultantPickerView.setData(list)

        if (!mDistributionPopup.isShowing) {
            mDistributionPopup.showAtLocation(webView, Gravity.BOTTOM, 0, 0)
        }
    }

    private fun addRecruit() {
        mWebHelper.doAfterGetCustomerDetail(webView) {
            startActivity<NewFromActivity>(KeyConstant.KEY_CUSTOMER_ID to it.customerId)
        }
    }

    private fun getCustomerDetailMoreActions(): List<Pair<String, Int>> {
        val actions = mutableListOf(ADD_TO_CONTACTS)

        // 分配权限
        if ("1" == EmmApplication.getData(EmmApplication.isDistributionCustomer)) {
            actions.add(DISTRIBUTION)
        }

        // 拥有认筹权限
        if ("1" == EmmApplication.getData(EmmApplication.FROMDETAILSTYPE) && "1" == EmmApplication.getData(EmmApplication.isAddPaydeposit)) {
            actions.add(ADD_RECRUIT)
        }

        return actions
    }

    companion object {
        private val ADD_TO_CONTACTS = Pair("添加到通讯录", R.drawable.more_message)
        private val DISTRIBUTION = Pair("分配", R.drawable.more_allot)
        private val ADD_RECRUIT = Pair("新增认筹", R.drawable.more_form)

        /*安全码*/
        private const val UA = "Mozilla/5.0 (Linux; Android 4.3; Nexus 7 Build/JSS15Q) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2307.2 Safari/537.360123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199778899090988878"

        private const val KEY_URL = "KEY_URL"
        private const val KEY_TITLE = "KEY_TITLE"

        @JvmOverloads
        fun jump(context: Context, url: String, title: String, param: Map<String, String> = mutableMapOf()) {
            context.startActivity<WebActivity>(KEY_URL to handleUrl(url, param), KEY_TITLE to title)
        }

        private fun handleUrl(url: String, queryParam: Map<String, String>): String {
            EmmApplication.updateUrl(url)

            val allParam = mutableMapOf<String, String>().apply {
                putAll(queryParam)
                putAll(Util.getCommonParam())
            }

            val body = mapOf<String, Any>("params" to allParam)

            return EmmApplication.urlStr + "?body=" + JSONObject(body).toString() + ""
        }

        fun jump2AddCustomer(context: Context) {
            val param = mutableMapOf<String, String>()
            param["busNumType"] = "1"
            param["busNum"] = "01"
            jump(context, "customer_add", "新建客户", param)
        }

        fun jump2CustomerDetail(context: Context, customerId: String) {
            val param = createJump2CustomerDetailParam(customerId)
            jump(context, "customer_detail", "客户详情", param)
        }

        @JvmOverloads
        fun createIntent(context: Context, url: String, title: String, param: Map<String, String> = mutableMapOf()): Intent {
            return Intent(context, WebActivity::class.java).apply {
                putExtra(KEY_URL, handleUrl(url, param))
                putExtra(KEY_TITLE, title)
            }
        }

        fun createJump2CustomerDetailIntent(context: Context, customerId: String): Intent {
            val param = createJump2CustomerDetailParam(customerId)
            return createIntent(context, "customer_detail", "客户详情", param)
        }

        private fun createJump2CustomerDetailParam(customerId: String): Map<String, String> {
            return mutableMapOf<String, String>().apply {
                put("busNumType", "1")
                put("busNum", "01")
                put("customerId", customerId)
            }
        }

    }

}